<template>
  <SectionContainer class="u-p20">
    <Tabs class="u-mb20">
      <TabsItem @click="$router.push({
        name: 'generalize-plan'
      })">广告计划</TabsItem>
      <TabsItem is-active>广告单元</TabsItem>
      <TabsItem @click="$router.push({
        name: 'generalize-creative'
      })">广告创意</TabsItem>
    </Tabs>

    <!-- 筛选 -->
    <el-form
      inline
      class="m-filter"
    >
      <el-form-item>
        <el-select
          filterable
          size="small"
          class="u-w145"
          v-model="filter.status"
          placeholder="请选择状态"
        >
          <el-option
            :value="0"
            label="全部状态"
          ></el-option>
          <el-option
            :value="2"
            label="启用"
          ></el-option>
          <el-option
            :value="1"
            label="停用"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-date-picker
          :clearable="false"
          v-model="filter.daterange"
          size="small"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd"
          :picker-options="DATERANGE_OPTIONS"
          class="u-w300"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-input
          v-model="filter.keyword"
          size="small"
          placeholder="请输入广告单元名称或ID"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button
          size="small"
          type="primary"
          @click="search"
        >查询</el-button>
      </el-form-item>
    </el-form>

    <!-- Table -->
    <TableFull
      :data="tableData"
      :column-data="tableColumn"
      :attach-width="200"
      :total="tableTotal"
      :current-page="page.pageNo"
      @current-change="currentChange"
      @size-change="sizeChange"
      @selection-change="tableSelectionChange"
    >
      <el-form
        inline
        class="m-filter"
        slot="handle"
      >
        <el-form-item v-permission="['promote_unit_add']">
          <el-button
            type="primary"
            size="small"
            @click="$router.push({
              name: 'generalize-cell-detail',
              query: {
                action: 'create',
                referrer: 'generalize-cell',
                planId: $route.query.planId,
                query: {
                  ...page,
                  ...$route.query
                }
              }
            })"
          >创建广告单元</el-button>
        </el-form-item>
        <el-form-item v-permission="['promote_unit_enable']">
          <el-button
            size="small"
            @click="openStatusMulti"
          >启用</el-button>
        </el-form-item>
        <el-form-item v-permission="['promote_unit_enable']">
          <el-button
            size="small"
            @click="closeStatusMulti"
          >停用</el-button>
        </el-form-item>
        <el-form-item v-permission="['promote_unit_setProfitRatio']">
          <el-button
            size="small"
            @click="openProfitMulti"
          >设置盈利比</el-button>
        </el-form-item>
        <el-form-item v-permission="['promote_unit_setExposureRatio']">
          <el-button
            size="small"
            @click="openExposureMulti"
          >设置曝光数比</el-button>
        </el-form-item>
        <el-form-item v-permission="['promote_unit_setBudget']">
          <el-button
            size="small"
            @click="openBudgetMulti"
          >设置每日预算</el-button>
        </el-form-item>
        <el-form-item>
          <CustomTableColumn :module="1" :columns.sync="tableColumn" />
        </el-form-item>
      </el-form>
      <template slot="column">
        <el-table-column
          :resizable="false"
          align="center"
          width="40"
          type="selection"
        ></el-table-column>
        <el-table-column
          :resizable="false"
          align="center"
          label="操作"
        >
          <el-table-column
            :resizable="false"
            align="center"
            label="总计"
            width="160"
            class-name="u-table--total"
          >
            <template slot-scope="scope">
              <el-tooltip
                v-permission="['promote_unit_view']"
                effect="dark"
                placement="top"
                content="查看"
              >
                <i
                  @click="$router.push({
                    name: 'generalize-cell-detail',
                    query: {
                      action: 'detail',
                      referrer: 'generalize-cell',
                      planId: scope.row.planId,
                      unitId: scope.row.unitId,
                      query: {
                        ...page,
                        ...$route.query
                      }
                    }
                  })"
                  class="u-table-handle iconfont iconfont-6"
                ></i>
              </el-tooltip>
              <el-tooltip
                v-permission="['promote_unit_edit']"
                effect="dark"
                placement="top"
                content="编辑"
              >
                <i
                  @click="$router.push({
                    name: 'generalize-cell-detail',
                    query: {
                      action: 'edit',
                      referrer: 'generalize-cell',
                      planId: scope.row.planId,
                      unitId: scope.row.unitId,
                      query: {
                        ...page,
                        ...$route.query
                      }
                    }
                  })"
                  class="u-table-handle iconfont iconfont-5"
                ></i>
              </el-tooltip>
              <el-tooltip
                v-permission="['promote_unit_delete']"
                effect="dark"
                placement="top"
                content="删除"
              >
                <i
                  @click="openRemoveItemData(scope.row.unitId)"
                  class="u-table-handle el-icon-circle-close"
                ></i>
              </el-tooltip>
              <el-tooltip
                v-permission="['promote_unit_copy']"
                effect="dark"
                placement="top"
                content="复制广告单元"
              >
                <i
                  @click="$router.push({
                    name: 'generalize-cell-detail',
                    query: {
                      action: 'copy',
                      referrer: 'generalize-cell',
                      planId: scope.row.planId,
                      unitId: scope.row.unitId,
                      query: {
                        ...page,
                        ...$route.query
                      }
                    }
                  })"
                  class="u-table-handle iconfont iconfont-7"
                ></i>
              </el-tooltip>
              <el-tooltip
                v-permission="['promote_unit_addCreative']"
                effect="dark"
                placement="top"
                content="添加广告创意"
              >
                <i
                  @click="$router.push({
                    name: 'generalize-creative-detail',
                    query: {
                      action: 'create',
                      referrer: 'generalize-cell',
                      planId: scope.row.planId,
                      unitId: scope.row.unitId,
                      query: {
                        ...page,
                        ...$route.query
                      }
                    }
                  })"
                  class="u-table-handle iconfont iconfont-34"
                ></i>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table-column>
        <!-- eslint-disable -->
        <el-table-column
          :resizable="false"
          align="center"
          v-for="(item, index) in tableColumn"
          v-if="item.visible"
          :key="index"
          :label="item.label"
          :sortable="item.sortable"
          :sort-by="item.prop"
        >
          <el-table-column
            :resizable="false"
            align="center"
            :label="getTableDataSumValue(item.prop, {rate: ['clickRate']})"
            :prop="item.prop"
            :width="item.width"
            class-name="u-table--total"
          >
            <template slot-scope="scope">
              <!-- 名称 -->
              <span
                class="u-tl u-link"
                v-if="item.prop === 'unitName'"
                @click="$router.push({
                  name: 'generalize-creative',
                  query: {
                    referrer: 'generalize-cell',
                    planId: scope.row.planId,
                    unitId: scope.row.unitId
                  }
                })"
              >{{scope.row.unitName}}</span>

              <!-- 开关 -->
              <template v-else-if="item.prop === 'switch'">
                <el-switch
                  v-if="[1, 2].indexOf(scope.row.status) !== -1"
                  @change="openStatus([scope.row.unitId], scope.row.status === 1 ? 2 : 1)"
                  :value="scope.row.status"
                  :active-value="2"
                  :inactive-value="1"
                ></el-switch>
              </template>

              <!-- 历史盈利比 -->
              <el-popover
                v-else-if="item.prop === 'profitPercentage'"
                placement="top"
                width="320"
                trigger="click"
              >
                <el-table
                  :data="unitHistoryProfitData"
                  :max-height="300"
                >
                  <el-table-column
                    :resizable="false"
                    width="200"
                    property="createTime"
                    label="日期"
                  ></el-table-column>
                  <el-table-column
                    :resizable="false"
                    width="120"
                    property="profitPercentage"
                    label="历史盈利比"
                  >
                    <template slot-scope="scope">{{scope.row[item.prop] + '%'}}</template>
                  </el-table-column>
                </el-table>
                <span
                  slot="reference"
                  class="c-text-high u-cursor"
                  @click="fetchUnitHistoryProfit(scope.row.unitId)"
                >{{scope.row.profitPercentage + '%'}}</span>
              </el-popover>

              <!-- 历史曝光数比 -->
              <el-popover
                v-else-if="item.prop === 'displayPercentage'"
                placement="top"
                width="320"
                trigger="click"
              >
                <el-table
                  :data="unitHistoryExposureData"
                  :max-height="300"
                >
                  <el-table-column
                    :resizable="false"
                    width="200"
                    property="createTime"
                    label="日期"
                  ></el-table-column>
                  <el-table-column
                    :resizable="false"
                    width="120"
                    property="displayPercentage"
                    label="历史曝光数比"
                  >
                    <template slot-scope="scope">{{scope.row[item.prop] + '%'}}</template>
                  </el-table-column>
                </el-table>
                <span
                  slot="reference"
                  class="c-text-high u-cursor"
                  @click="fetchUnitHistoryExposure(scope.row.unitId)"
                >{{scope.row.displayPercentage + '%'}}</span>
              </el-popover>

              <!-- 点击率 -->
              <template v-else-if="item.prop === 'clickRate' && scope.row[item.prop] !== null">{{decimalMultiply(scope.row[item.prop], 100) + '%'}}</template>

              <!-- 出价 -->
              <template v-else-if="item.prop === 'defaultPrice'">
                {{mapValue(GENERALIZE_CELL_COST, scope.row.costType)}}：{{scope.row.defaultPrice}}<br>
                <i
                  v-permission="['promote_unit_edit']"
                  @click="openDefaultPrice(scope.row)"
                  class="el-icon-edit c-text-high u-cursor"
                >修改</i>
              </template>

              <!-- 每日预算 -->
              <template v-else-if="item.prop === 'budget'">
                {{scope.row.whetherBudget === 1 ? "不限预算" : scope.row.budget}}<br>
                <i
                  v-permission="['promote_unit_edit']"
                  @click="openBudget(scope.row)"
                  class="el-icon-edit c-text-high u-cursor"
                >修改</i>
              </template>

              <!-- 投放周期 -->
              <template v-else-if="item.prop === 'cycle'">{{getCycleChoice(scope.row)}}</template>

              <!-- 状态 -->
              <template v-else-if="item.prop === 'auditStatus'">
                <span :class="{ 'u-status--progress': scope.row.promotionStatus.status === '投放中' }">{{scope.row.promotionStatus.status}}</span>
              </template>

              <!-- 计划名称 -->
              <template v-else-if="item.prop === 'planName'">
                <div class="u-tl">{{scope.row[item.prop]}}</div>
              </template>

              <!-- 竞价成功率 -->
              <template v-else-if="item.prop === 'bidsSuccessRate' && scope.row.bidsSuccessRate !== null">
                <el-tooltip
                  effect="dark"
                  placement="top"
                >
                  <div
                    slot="content"
                    class="u-w200"
                  >{{getBidsSuccessRateTooltip(scope.row.bidsSuccessRate)}}</div>
                  <span :class="{
                    'c-hint-error': scope.row.bidsSuccessRate < 0.3,
                    'c-hint-warn': scope.row.bidsSuccessRate >= 0.3 && scope.row.bidsSuccessRate <= 0.5
                  }">
                    {{decimalMultiply(scope.row.bidsSuccessRate, 100) + '%'}}
                  </span>
                </el-tooltip>
              </template>

              <!-- 其他 -->
              <template v-else>{{scope.row[item.prop]}}</template>
            </template>
          </el-table-column>
        </el-table-column>
      </template>
    </TableFull>

    <!-- 修改出价 -->
    <Dialog
      :visible.sync="defaultPriceVisible"
      title="修改出价"
      :width="440"
    >
      <el-form
        class="u-pt20"
        label-width="110px"
        ref="defaultPriceForm"
        :model="defaultPriceData"
        :rules="defaultPriceRules"
      >
        <el-form-item label="付费方式：">{{mapValue(GENERALIZE_CELL_COST, defaultPriceData.costType)}}</el-form-item>
        <el-form-item
          label="出价："
          prop="defaultPrice"
          class="u-mr30"
        >
          <el-input v-model="defaultPriceData.defaultPrice">
            <template slot="append">元</template>
          </el-input>
          <template v-if="tableRowData.remarks">
            <Tip inline>{{suggestPrice(tableRowData.remarks)}}</Tip>
            <el-tooltip
              class="item"
              effect="dark"
              placement="top"
            >
              <Tip
                inline
                slot="content"
                class="u-lh24 c-background-high"
              >
                注：<br>
                1、建议高于底价范围出价<br>
                2、如果希望获得更多的量，可适当提高出价增加广告竞争力
              </Tip>
              <i class="iconfont iconfont-10 c-hint-major u-ml5"></i>
            </el-tooltip>
          </template>
        </el-form-item>
        <el-form-item
          label-width="0"
          align="center"
          class="u-h32"
        >
          <el-button
            type="primary"
            size="small"
            @click="updateDefaultPrice"
          >确定</el-button>
        </el-form-item>
      </el-form>
    </Dialog>

    <!-- 修改预算 -->
    <Dialog
      :visible.sync="budgetVisible"
      title="修改预算"
      :width="400"
    >
      <el-form
        class="u-pt20 u-pl20 u-pr20"
        ref="budgetForm"
        :model="budgetData"
        :rules="budgetRules"
      >
        <el-form-item>
          <el-radio
            v-model="budgetData.whetherBudget"
            :label="1"
          >不限预算</el-radio>
        </el-form-item>
        <el-form-item prop="budget">
          <el-radio
            v-model="budgetData.whetherBudget"
            :label="0"
          >自定义</el-radio>
          <el-input
            :disabled="budgetData.whetherBudget === 1"
            v-model="budgetData.budget"
            style="width: 262px;"
          >
            <template slot="append">元</template>
          </el-input>
        </el-form-item>
        <el-form-item
          align="center"
          class="u-h32"
        >
          <el-button
            type="primary"
            size="small"
            @click="updateBudget"
          >确定</el-button>
        </el-form-item>
      </el-form>
    </Dialog>

    <!--设置盈利比-->
    <DialogRatio
      title="设置盈利比"
      :visible.sync="profitOpenVisible"
      @confirm="ensureProfitMulti"
    ></DialogRatio>

    <!--设置曝光数比-->
    <DialogRatio
      title="设置曝光数比"
      :visible.sync="exposureOpenVisible"
      @confirm="ensureEnsureMulti"
    ></DialogRatio>

    <!--启用-->
    <DialogConfirm
      :visible.sync="statusOpenVisible"
      :buttons="['启 用', '关 闭']"
      :button-primary="[0]"
      @confirm="confirmStatusOpen"
      :content="`是否要启用这${statusKeys.length}个单元？`"
    ></DialogConfirm>

    <!--停用-->
    <DialogConfirm
      :visible.sync="statusCloseVisible"
      :buttons="['停 用', '关 闭']"
      :button-primary="[0]"
      @confirm="confirmStatusClose"
      :content="`是否要停用这${statusKeys.length}个单元？`"
    ></DialogConfirm>

    <!--删除-->
    <DialogConfirm
      :visible.sync="removeDialogVisible"
      :buttons="['删 除', '关 闭']"
      :button-primary="[0]"
      @confirm="confirmRemoveItemData"
      content="是否删除此单元?"
      tip="此单元关联的全部广告创意将被删除，数据报表中已投放数据将正常统计！"
    ></DialogConfirm>
  </SectionContainer>
</template>

<script>
import Moment from "moment";
import { mapActions } from "vuex";

import Dialog from "@/components/dialog";
import DialogConfirm from "@/components/dialog-confirm";
import DialogRatio from "@/components/dialog-ratio";
import TableFull from "@/components/table-full";
import SectionContainer from "@/components/section-container";
import Tip from "@/components/tip";
import Tabs from "@/components/tabs";
import TabsItem from "@/components/tabs-item";
import CustomTableColumn from "@/components/custom-table-column";

import { GENERALIZE_CELL_COST } from "@/assets/js/common-option";
import DATERANGE_OPTIONS from "@/assets/js/daterange-option";
import { sessionStorage, mapValue, suggestPrice, hasPermission } from "@/utils";
import { decimalMultiply } from "@/utils/decimal";
import {
  fetchUnitList,
  fetchUnitStatus,
  fetchUnitProfit,
  fetchUnitExposure,
  fetchUnitHistoryProfit,
  fetchUnitHistoryExposure,
  fetchUnitRemove,
  fetchUnitUpdateBudget,
  fetchUnitUpdatePrice
} from "@/api";

export default {
  components: {
    Dialog,
    DialogConfirm,
    DialogRatio,
    TableFull,
    SectionContainer,
    Tabs,
    TabsItem,
    Tip,
    CustomTableColumn
  },
  data() {
    return {
      DATERANGE_OPTIONS,
      GENERALIZE_CELL_COST,

      user: sessionStorage.get("USER"),

      // 弹窗
      profitOpenVisible: false,
      exposureOpenVisible: false,
      statusOpenVisible: false,
      statusCloseVisible: false,
      statusKeys: [],
      removeDialogVisible: false,
      removeDialogId: "",

      // 表格单项修改
      defaultPriceVisible: false,
      defaultPriceData: {},
      defaultPriceRules: {
        defaultPrice: {
          required: true,
          validator: (rule, value, callback) => {
            if (!value || String(value).trim() === "") {
              callback(new Error("请输入出价"));
            } else if (value < 0.1 || isNaN(value)) {
              callback(new Error("最低0.1"));
            } else if (
              String(value).length > String(Number(value).toFixed(2)).length
            ) {
              callback(new Error("请保留2位小数"));
            } else {
              callback();
            }
          },
          trigger: ["blur", "change"]
        }
      },
      budgetVisible: false,
      budgetData: {},
      budgetRules: {
        budget: {
          required: true,
          validator: (rule, value, callback) => {
            // 限制预算才验证预算
            if (this.budgetData.whetherBudget === 0) {
              if (!value || String(value).trim() === "") {
                callback(new Error("请输入每日预算"));
              } else if (value < 0.01 || isNaN(value)) {
                callback(new Error("最低0.01"));
              } else if (
                String(value).length > String(Number(value).toFixed(2)).length
              ) {
                callback(new Error("请保留2位小数"));
              } else {
                callback();
              }
            } else {
              callback();
            }
          },
          trigger: ["blur", "change"]
        }
      },

      // 历史盈利比
      unitHistoryProfitData: [],

      // 历史曝光数比
      unitHistoryExposureData: [],

      filter: {
        status: 0,
        daterange: [
          Moment().format("YYYY-MM-DD"),
          Moment().format("YYYY-MM-DD")
        ],
        keyword: ""
      },

      page: {
        pageSize: 50,
        pageNo: Number(this.$route.query.pageNo) || 1
      },

      // 广告单元/Table
      tableData: [],
      tableColumn: [
        {
          label: "是否启用",
          prop: "switch",
          width: 55,
          visible: hasPermission(["promote_unit_enable"])
        },
        {
          label: "单元名称",
          prop: "unitName",
          width: 150,
          visible: true
        },
        {
          label: "单元ID",
          prop: "unitId",
          visible: true
        },
        {
          label: "所属层级",
          prop: "planName",
          width: 150,
          visible: true
        },
        {
          label: "状态",
          prop: "auditStatus",
          visible: true
        },
        {
          label: "盈利比",
          prop: "profitPercentage",
          visible: hasPermission(["promote_unit_profitRatio"])
        },
        {
          label: "曝光数比",
          prop: "displayPercentage",
          visible: hasPermission(["promote_unit_exposureRatio"])
        },
        {
          label: "出价(元)",
          prop: "defaultPrice",
          width: 150,
          visible: true
        },
        {
          label: "每日预算(元)",
          prop: "budget",
          visible: true
        },
        {
          label: "投放周期",
          prop: "cycle",
          width: 200,
          visible: true
        },
        {
          label: "竞价成功率",
          prop: "bidsSuccessRate",
          sortable: true,
          visible: true
        },
        {
          label: "APP开始下载数",
          prop: "downloadStartNumber",
          visible: false,
          custom: true
        },
        {
          label: "APP下载完成数",
          prop: "downloadCompleteNumber",
          visible: false,
          custom: true
        },
        {
          label: "APP开始安装数",
          prop: "installationStartNumber",
          visible: false,
          custom: true
        },
        {
          label: "APP安装完成数",
          prop: "installationCompleteNumber",
          visible: false,
          custom: true
        },
        {
          label: "APP激活数",
          prop: "activationNumber",
          visible: false,
          custom: true
        },
        {
          label: "APP注册数",
          prop: "registeredNumber",
          visible: false,
          custom: true
        },
        {
          label: "总消耗(元)",
          prop: "biddingPrice",
          sortable: true,
          visible: true
        },
        {
          label: "曝光数",
          prop: "displayNumber",
          sortable: true,
          visible: true
        },
        {
          label: "点击数",
          prop: "clickNumber",
          sortable: true,
          visible: true
        },
        {
          label: "点击率",
          prop: "clickRate",
          sortable: true,
          visible: true
        },
        {
          label: "点击均价(元)",
          prop: "cpcAveragePrice",
          sortable: true,
          visible: true
        },
        {
          label: "千次曝光均价(元)",
          prop: "cpmAveragePrice",
          sortable: true,
          visible: true
        }
      ],
      tableSelectionData: [],
      tableTotal: 0,
      tableRowData: {}
    };
  },
  computed: {
    // 拼接选中的数据
    checkedTableData() {
      return this.tableSelectionData.map(item => item.unitId);
    }
  },
  watch: {
    $route() {
      this.search();
    },
    "budgetData.whetherBudget"(v) {
      if (this.$refs.budgetForm) {
        if (v === 1) {
          this.$refs.budgetForm.clearValidate("budget");
        } else {
          this.$refs.budgetForm.validateField("budget");
        }
      }
    }
  },
  methods: {
    ...mapActions(["GeneralizeNav/UPDATE_DATA"]),
    decimalMultiply,
    mapValue,
    suggestPrice,

    // 投放周期
    getCycleChoice({ cycleChoice, startTime, endTime }) {
      if (cycleChoice === 1 && startTime !== "") {
        return `${startTime}~${endTime}`;
      }
      return "长期投放";
    },
    // 重置
    search() {
      this.page.pageNo = 1;
      this.getTable();
    },
    // 获取数据
    getTable() {
      this.tableData = [];
      this.tableTotal = 0;
      fetchUnitList({
        query: {
          userId: this.user.userId
        },
        body: {
          ...this.page,
          startTime: this.filter.daterange[0],
          endTime: this.filter.daterange[1],
          searchNameOrId: this.filter.keyword,
          status: this.filter.status,
          planId: this.$route.query.planId
        }
      }).then(res => {
        this.tableTotal = res.data.count;
        if (res.data.list && res.data.list.length) {
          res.data.list.map((item, index) => {
            item.index = index;
            item.__edit_defaultPrice = item.defaultPrice;
            item.__edit_budget = item.budget || "";
            item.__edit_whetherBudget = item.whetherBudget;
          });
          this.tableData = this.modTableDataSumList(res.data.sumList, res.data.list);
        }
      });
    },
    // 给第一行数据添加总计相关数据
    modTableDataSumList(sumList, data) {
      let sum = sumList.length ? sumList[0] : {};
      let sumObj = {};
      for (let key in sum) {
        sumObj[`__` + key] = sum[key];
      }
      data[0] = {
        ...data[0],
        ...sumObj
      };
      return data;
    },
    // 获取总计的相关值
    getTableDataSumValue(prop, { rate }) {
      let sum = this.tableData[0] || {};
      let sumProp = `__${prop}`;
      if (sumProp in sum) {
        let value = sum[sumProp];
        // 添加百分比
        if (rate.indexOf(prop) !== -1) {
          return decimalMultiply(value, 100) + "%";
        }
        return String(value);
      }
      return "";
    },
    // 表格多选
    tableSelectionChange(val) {
      this.tableSelectionData = val;
    },
    // 确认启用
    confirmStatusOpen(index) {
      if (index === 0) {
        this.changeStatus(this.statusKeys, 2).then(() => {
          this.statusOpenVisible = false;
          this.getTable();
        });
      } else {
        this.statusOpenVisible = false;
      }
    },
    // 确认停用
    confirmStatusClose(index) {
      if (index === 0) {
        this.changeStatus(this.statusKeys, 1).then(() => {
          this.statusCloseVisible = false;
          this.getTable();
        });
      } else {
        this.statusCloseVisible = false;
      }
    },
    // 启用多个
    openStatusMulti() {
      if (!this.checkedTableData.length) {
        return this.$message({
          message: "请选择单元",
          duration: 2000
        });
      }
      this.openStatus(this.checkedTableData, 2);
    },
    // 停用多个
    closeStatusMulti() {
      if (!this.checkedTableData.length) {
        return this.$message({
          message: "请选择单元",
          duration: 2000
        });
      }
      this.openStatus(this.checkedTableData, 1);
    },
    // 批量设置盈利比
    openProfitMulti() {
      if (!this.checkedTableData.length) {
        return this.$message({
          message: "请选择单元",
          duration: 2000
        });
      }
      this.profitOpenVisible = true;
    },
    ensureProfitMulti(ratio) {
      fetchUnitProfit({
        query: {
          ids: this.checkedTableData.join(),
          ratio: ratio
        }
      }).then(() => {
        this.profitOpenVisible = false;
        this.getTable();
      });
    },
    // 历史盈利比
    fetchUnitHistoryProfit(unitId) {
      this.unitHistoryProfitData = [];
      fetchUnitHistoryProfit({
        query: {
          unitId
        }
      }).then(res => {
        this.unitHistoryProfitData = res.data.data;
      });
    },
    // 批量设置曝光数比
    openExposureMulti() {
      if (!this.checkedTableData.length) {
        return this.$message({
          message: "请选择单元",
          duration: 2000
        });
      }
      this.exposureOpenVisible = true;
    },
    ensureEnsureMulti(ratio) {
      fetchUnitExposure({
        query: {
          ids: this.checkedTableData.join(),
          ratio: ratio
        }
      }).then(() => {
        this.exposureOpenVisible = false;
        this.getTable();
      });
    },
    // 历史曝光数比
    fetchUnitHistoryExposure(unitId) {
      this.unitHistoryExposureData = [];
      fetchUnitHistoryExposure({
        query: {
          unitId
        }
      }).then(res => {
        this.unitHistoryExposureData = res.data.data;
      });
    },
    // 删除一条
    openRemoveItemData(id) {
      this.removeDialogVisible = true;
      this.removeDialogId = id;
    },
    // 确认删除一条
    confirmRemoveItemData(index) {
      if (index === 0) {
        fetchUnitRemove({
          query: {
            id: this.removeDialogId
          }
        }).then(() => {
          this.removeDialogVisible = false;
          this["GeneralizeNav/UPDATE_DATA"]();
          this.getTable();
        });
      } else {
        this.removeDialogVisible = false;
      }
    },
    // 切换状态
    openStatus(keys, value) {
      this.statusKeys = keys;
      if (1 === value) {
        this.statusCloseVisible = true;
      } else if (2 === value) {
        this.statusOpenVisible = true;
      }
    },
    // 状态操作
    changeStatus(keys, value) {
      return fetchUnitStatus({
        query: {
          ids: keys.join(),
          status: value
        }
      }).then(() => {
        this.$message({
          message: "操作成功",
          duration: 1000
        });
      });
    },
    // 分页
    currentChange(val) {
      this.page.pageNo = val;
      this.getTable();
    },
    sizeChange(val) {
      this.page.pageSize = val;
      this.getTable();
    },
    // 更新每日预算
    updateBudget() {
      this.$refs["budgetForm"].validate(valid => {
        if (valid) {
          fetchUnitUpdateBudget({
            query: {
              unitId: this.budgetData.unitId,
              budget:
                this.budgetData.whetherBudget === 1
                  ? 0
                  : this.budgetData.budget,
              whetherBudget: this.budgetData.whetherBudget
            }
          }).then(() => {
            this.budgetVisible = false;
            this.$message("预算修改成功");
            this.getTable();
          });
        }
      });
    },
    openBudget({ unitId, whetherBudget = 1, budget = 0 }) {
      this.budgetVisible = true;
      this.budgetData = {
        unitId,
        whetherBudget,
        budget
      };
    },
    openBudgetMulti() {
      if (!this.checkedTableData.length) {
        return this.$message({
          message: "请选择单元",
          duration: 2000
        });
      }
      this.openBudget({ unitId: this.checkedTableData.join() });
    },
    // 更新出价
    updateDefaultPrice() {
      this.$refs["defaultPriceForm"].validate(valid => {
        if (valid) {
          fetchUnitUpdatePrice({
            query: {
              unitId: this.defaultPriceData.unitId,
              defaultPrice: this.defaultPriceData.defaultPrice
            }
          }).then(() => {
            this.defaultPriceVisible = false;
            this.tableRowData.defaultPrice = this.defaultPriceData.defaultPrice; // 页面修改，无需刷新
            this.$message("出价修改成功");
          });
        }
      });
    },
    openDefaultPrice(row) {
      let { unitId, defaultPrice, costType } = row;
      this.defaultPriceVisible = true;
      this.tableRowData = row;
      this.defaultPriceData = {
        unitId,
        defaultPrice,
        costType
      };
    },
    // 竞价成功率提示
    getBidsSuccessRateTooltip(rate) {
      if (rate < 0.3) {
        return "广告竞争力很低，建议提高出价以获得更多的曝光";
      } else if (rate > 0.5) {
        return "广告竞争力正常，可持续投放";
      }
      return "广告竞争力较低，建议尝试放宽定向、提高出价等方式优化";
    }
  },
  created() {
    this.getTable();
  }
};
</script>